package com.vb.ecm.web.custom.workflow;

//______________________________________________________________________________
//
// Module: module-wdk
// File: ISAFormPostProcessor.java
// $LastChangedRevision$
// $HeadURL$
//______________________________________________________________________________
//
// CreatedBy: Naresh
// CreationDate: Apr 23, 2009
// $LastChangedBy$
// $LastChangedDate$
//______________________________________________________________________________
//
// Copyright: (c) Verinon Documentum 2009, all rights reserved
//______________________________________________________________________________

/**
 *
 * @author Naresh
 * @version 1.0
 * @since May , 2009
 *
 */

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfActivity;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfProcess;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.client.IDfWorkflow;
import com.documentum.fc.client.IDfWorkflowBuilder;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.DfList;
import com.documentum.fc.common.DfLogger;
import com.documentum.fc.common.DfTime;
import com.documentum.fc.common.IDfId;
import com.documentum.fc.common.IDfList;
import com.documentum.fc.common.IDfTime;
import com.documentum.services.xforms.IFormService;
import com.documentum.tools.adaptor.AdaptorException;
import com.documentum.tools.adaptor.configuration.IAdaptorConfiguration;
import com.documentum.xforms.engine.adaptor.processor.IDocbaseDocumentProcessor;
import com.documentum.xforms.engine.docbase.DocbaseXFormsContext;

public class LeaveFormPostProcessor implements IDocbaseDocumentProcessor {
	private static final Logger LOGGER = Logger.getLogger(LeaveFormPostProcessor.class);

	/**
	 * Used internally to parse the XML DOM of the passed XForm data
	 */
	int nodeLevel = 0;

	/**
	 * The show comments from the submitted XForm XML data
	 */
	String showcommentsXml = null;

	/**
	 * The comments from the submitted XForm XML data
	 */
	String commentsXml = null;

	IDfClientX clientx;

	// IDfId forminstID = null;

	String FORM_TEMPLATE_NAME = null;// "ISASample";

	String FORM_INSTANCE_PATH = "/";

	String FORM_TYPE = "vb_it_leave_form";

	String WORKFLOW_TEMPLATE_NAME = "IT_LEAVE_WORKFLOW";

	String WORKFLOW_INSTANCE_NAME = "IT_LEAVE_WORKFLOW";

	String formInstanceName = null;

	// private IDfSysObject oldXForm;

	private IDfSysObject leaveFormObject;

	private String empName;

	private String empPosition;
	private String leaveStatus;

	private String deptName;

	private String location;
	ArrayList emailList = new ArrayList();

	public LeaveFormPostProcessor() {

	}

	// String d_email = "dl.tcsesv.in.teams.admin.support@imcnam.ssmb.com",

	/**
	 * log4j logger instance being used for debugging / informational logging.
	 */
	/**
	 * Constructor used only for logging instance creation.
	 */

	/**
	 * {@inheritDoc}
	 */
	public void init(IAdaptorConfiguration iadaptorconfiguration) throws AdaptorException {

		System.out.println("Inside post processor");

	}

	/**
	 * {@inheritDoc}
	 */
	public void destroy() throws AdaptorException {
		System.out.println("destroy");

	}

	/**
	 * {@inheritDoc}
	 */
	public Document execute(Document document, DocbaseXFormsContext docbasexformscontext) throws AdaptorException {

		clientx = new DfClientX();
		System.out.println("document" + document);
		Document originalDoc = document;
		IDfSession session = null;

		// Fill member variables holding provider code and member number with
		// values from passed XML data.
		processDomNode(document);

		try {

			session = docbasexformscontext.getSessionManager().getSession(docbasexformscontext.getDocbaseName());

			IDfId xformId = docbasexformscontext.getInstanceId();

			leaveFormObject = (IDfSysObject) session.getObject(docbasexformscontext.getInstanceId());
			IDfSysObject oldXFormTemplateID = (IDfSysObject) session.getObject(docbasexformscontext.getTemplateId());

			FORM_TEMPLATE_NAME = oldXFormTemplateID.getObjectName();
			if (leaveFormObject != null) {
				empName = leaveFormObject.getString("emp_name");
				empPosition=leaveFormObject.getString("emp_position");
                 deptName=leaveFormObject.getString("dept_name");
				formInstanceName =leaveFormObject.getObjectName();

				if ((leaveFormObject.getTypeName().equalsIgnoreCase("vb_it_leave_form")&&((deptName!=" ")||(deptName!="")||(deptName!=null)))) {
					IDfSysObject leaveFormObjectTemp = leaveFormObject;
					leaveFormObjectTemp.setString("object_name",empName+"_" +formInstanceName);
					leaveFormObjectTemp.setString("leave_status", "Pending For Approval");
					leaveFormObjectTemp.save();
				}

				String workflowId = startWorkflow(session, WORKFLOW_TEMPLATE_NAME, FORM_TYPE, "", xformId.toString(), WORKFLOW_INSTANCE_NAME);
				System.out.println("workflow started for all approvers" + workflowId);
			}
		} catch (Exception e) {
			new AdaptorException(e);
		} finally {
			if (session != null) {
				try {
					docbasexformscontext.getSessionManager().release(session);
				} catch (Exception e) {
					// Nothing we can do here
					System.out.println(e);
				}
			}
		}

		return originalDoc;
	}

	/**
	 * Starts a workflow for the specified workflow template. Requester(user who
	 * created session) must have at least RELATE permissions on the workflow
	 * template
	 * 
	 * @param session
	 *            IDfsession object of the requested user.
	 * @param workflowTemplateName
	 *            Process name to start
	 * @param packageType
	 *            Object type of the workflwo package
	 * @param supervisorName
	 *            Name of the workflow supervisor
	 * @param documentId
	 *            Is 'r_object_id' of the document to attache workflow package
	 * @param workflowName
	 *            Is the name of the new workflow to be
	 * @return Returns workflow id, if workflow started successfully else
	 *         returns 'FAILURE'.
	 * @throws DfException
	 */
	public static String startWorkflow(IDfSession session, String workflowTemplateName, String packageType, String supervisorName, String documentId, String workflowName)
			throws DfException {
		// LOGGER.info("ENTER");
		IDfId processId = null;
		String status = null;
		try {
			System.out.println("in start workflow" + workflowTemplateName);

			// get the process ID
			IDfProcess processObject = (IDfProcess) session.getObjectByQualification("dm_process where object_name='" + workflowTemplateName + "' ");
			if (processObject != null) {
				processId = processObject.getObjectId();
			} else {
				throw new DfException("Workflow template not found with name " + workflowTemplateName);
			}
			IDfWorkflowBuilder wfBuilder = session.newWorkflowBuilder(processId);
			IDfWorkflow workflow = wfBuilder.getWorkflow();
			// setting custom name for the workflow
			if (workflowName != null && workflowName.length() > 0) {
				workflow.setObjectName(workflowName);
			}
			wfBuilder.initWorkflow();
			wfBuilder.runWorkflow();

			if (supervisorName != null && !"".equals(supervisorName)) {
				workflow.setSupervisorName(supervisorName);
			}
			String activityName = null;
			String packageName = null;
			String portName = null;
			IDfList activityIds = wfBuilder.getStartActivityIds();
			IDfId activityId = (IDfId) activityIds.get(0);
			IDfActivity activity = (IDfActivity) session.getObject(activityId);
			activityName = activity.getString("object_name");
			for (int cntrPort = 0; cntrPort < activity.getPortCount(); cntrPort++) {
				if (activity.getPortType(cntrPort).equals("INPUT")) {
					portName = activity.getPortName(cntrPort);
					packageName = activity.getPackageName(cntrPort);
					System.out.println("packageName==" + packageName);
					break;
				}
			}
			IDfList list = new DfList();
			list.appendId(new DfId(documentId));
			workflow.addPackage(activityName, portName, packageName, packageType, "", false, list);
			
			status = workflow.getObjectId().getId();
		} catch (DfException dfe) {
			throw new DfServiceException(dfe);
		}
		return status;
	}

	/**
	 * @param session
	 * @return
	 * @description Create Form instance
	 * 
	 */
	protected IDfId createFormInstance(IDfSession session, String userNmae) {
		IDfId forminstid = null;
		try {
		} catch (Exception e) {
			DfLogger.error(this, "error while creating form instance:" + e, null, null);
		}
		return forminstid;
	}

	/**
	 * Process copying attribute values.
	 * 
	 * @param form
	 *            objects
	 * @throws MessagingException
	 * 
	 * @throws DfException
	 */

	private boolean setUserAttributeValues(IDfSysObject formObj, String userName) throws DfException {
		formObj.setString("user_name", userName);
		return true;

	}

	/**
	 * Process Dom Node.
	 * 
	 * @param node
	 *            Node to be process
	 * @throws DfException
	 */

	private void processDomNode(Node node) {
		if (node.getNodeType() == node.CDATA_SECTION_NODE) {
			String nodeName = node.getParentNode().getNodeName();
			String nodeValue = node.getNodeValue();

			if (nodeName.equals("show_comments")) {
				showcommentsXml = nodeValue;
			} else if (nodeName.equals("comments")) {
				commentsXml = nodeValue;
			}
		}
		NodeList list = node.getChildNodes();
		nodeLevel++;
		for (int i = 0; i < list.getLength(); i++) {
			processDomNode(list.item(i));
		}
		nodeLevel--;
	}

	private void getUserDetails(String userName, IDfSession session) throws DfException {
		// IDfSession session = null;
		IDfCollection collection = null;
		try {
			System.out.println("in");

			IDfQuery q1 = clientx.getQuery();
			q1.setDQL("select user_name,user_address,firstname,client_name,lastname,ritsid,geid,directline_manager_name,directline_manager_mailid,country,office_numebr,department from isa_user where user_name='"
					+ userName + "'");
			collection = q1.execute(session, IDfQuery.DF_EXEC_QUERY);
			while (collection.next()) {

			}
		} catch (Exception e) {
		} finally {

			if (collection != null) {
				try {
					collection.close();
				} catch (DfException e) {

					e.printStackTrace();
					System.out.println("Exception in Catch Block");
					LOGGER.error(e.fillInStackTrace());

				}
				collection = null;
			}
		}
	}
}
